//
//  HMGamemgr.m
//  SNS_Login-register
//
//  Created by hy on 2021/10/27.
//  Copyright © 2021 lzxuan. All rights reserved.
//

#import "HWGameMgr.h"
#import "HWLoginView.h"
#import "ZYSuspensionView.h"
#import "UserAgreementViewController.h"
#import "WHToast.h"
#import "HWExchangeView.h"
#import "HWRealNameView.h"
#import "HWBindPhoneView.h"
#import "HWUserView.h"
#import "HWConstant.h"
#import "WHToastConfig.h"
#import "HWKeychain.h"
#import "AFHTTPSessionManager.h"
#import "LZXHttpDownload.h"


@interface HWGameMgr ()<ZYSuspensionViewDelegate>

@property (strong, nonatomic) HWLoginView *loginView;
@property (strong, nonatomic) ZYSuspensionView *ballView;
@property (strong, nonatomic) UserAgreementViewController *userAgreementViewController;
@property (strong, nonatomic) HWExchangeView *exchangeView;
@property (strong, nonatomic) HWRealNameView *realName;
@property (strong, nonatomic) HWBindPhoneView *bindPhoneView;
@property (strong, nonatomic) HWUserView *userView;


@end

@implementation HWGameMgr{
    
    EgretNativeIOS* _native;
}


static HWGameMgr *_instance;

+ (instancetype)shared
{
    if (!_instance) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _instance = [[self alloc] init];
        });
    }
    return _instance;
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    // test ball
//    [_instance showBall];
    return _instance;
}

/**  获取UUID*/
+(NSString *)getDeviceString{
    NSString * deviceUUIDStr = [HWKeychain passwordForService:kBundleId account:kUUID];
    if (deviceUUIDStr == nil || [deviceUUIDStr isEqualToString:@""])
    {
        deviceUUIDStr = [[[UIDevice currentDevice].identifierForVendor.UUIDString stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
        [HWKeychain setPassword: deviceUUIDStr  forService:kBundleId account:kUUID];
    }
    return deviceUUIDStr;
}

+(UIWindow*)getCurrentWindow

{

    if([[[UIApplication sharedApplication] delegate] window]) {
        return[[[UIApplication sharedApplication] delegate] window];
        
    }else{
        if(@available(iOS 13.0,*)){
            NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene* windowScene = (UIWindowScene*)array[0];
            //如果是普通App开发，可以使用
//            SceneDelegate * delegate = (SceneDelegate *)windowScene.delegate;
//            UIWindow * mainWindow = delegate.window;
            //由于在sdk开发中，引入不了SceneDelegate的头文件，所以需要用kvc获取宿主app的window.

            UIWindow* mainWindow = [windowScene valueForKeyPath:@"delegate.window"];
            if(mainWindow) {

                return mainWindow;
            }else{
                return [UIApplication sharedApplication].windows.firstObject;
            }

        }else{
            return[UIApplication sharedApplication].keyWindow;
        }
    }
}
+ (NSString *)randomAccount:(NSInteger)number {
    
    NSString *ramdom;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 1; i ; i ++) {
        int a = (arc4random() % 122);
        if ( (a>47 && a<58)) {
            char c = (char)a;
            [array addObject:[NSString stringWithFormat:@"%c",c]];
            if (array.count == number) {
                break;
            }
        } else continue;
    }
    ramdom = [array componentsJoinedByString:@""];
    return ramdom;
    
}
+ (NSString *)randomString:(NSInteger)number {
    
    NSString *ramdom;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 1; i ; i ++) {
        int a = (arc4random() % 122);
        if (a > 96 || (a>47 && a<58) || (a>64 && a<91)) {
            char c = (char)a;
            [array addObject:[NSString stringWithFormat:@"%c",c]];
            if (array.count == number) {
                break;
            }
        } else continue;
    }
    ramdom = [array componentsJoinedByString:@""];
    return ramdom;
    
}

#pragma mark ---------------------- network ---------------------
#pragma mark - 注册
//登录post 请求
/*
 {
    H5_dev: "UUID_1d383221e8f22e0f1cbfb82e2d4d2ecb"
    agentgame: "IOS.123-v1-1633017600"
    app_id: "1"
    device: {
         device_id: "UUID_1d383221e8f22e0f1cbfb82e2d4d2ecb",
         os: "ios"
     }
    password: "D5NSnR622z1"
    username: "100056583"
 */
- (void)httpRegister:(NSDictionary*)data {
    
    NSString* username = [data objectForKey:@"username"];
    NSString* password = [data objectForKey:@"password"];
    NSString* app_id = kAppId;
    NSString* agentgame = kAgentgame;
    NSString* H5_dev = [HWGameMgr getDeviceString];
    
    NSDictionary* param = @{
        @"username":username,
        @"password":password,
        @"app_id":app_id,
        @"agentgame":agentgame,
        @"H5_dev":H5_dev,
        @"device":@{
            @"device_id":H5_dev,
            @"os":@"ios",
        }
                            
    };
    
    
//    LZXHttpDownload *httpRequest = [[LZXHttpDownload alloc] init];
//    [httpRequest postDataWithUrl:kLoginUrl params:param success:^(NSData *downloadData) {
//        if (downloadData) {
//            //json 解析
////            NSData *data = downloadData;
////            NSError *error = nil;
////            NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
////            NSString *dataString = [[NSString alloc] initWithData:data encoding:enc];
////            NSData *utf8Data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//            NSError * errMsg  = [NSError new];
////            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:downloadData options:NSJSONReadingMutableContainers error:&errMsg];
//            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:downloadData options:NSJSONReadingMutableLeaves error:&errMsg];
//            NSLog(@"errMsg zkzk::%@",errMsg);
//            NSString* code = [NSString stringWithFormat:@"%@",dict[@"code"]];
//            if ([code isEqualToString:@"200"]) {
////                //保存 m_auth 这是 登录之后服务器给客户端的token (手机令牌)
////                //保存到本地  NSUserDefaults保存在沙盒目录下Library/Preferences/xxx.plist
////                [[NSUserDefaults standardUserDefaults] setObject:dict[@"m_auth"] forKey:@"snstoken"];
////                //同步到本地磁盘
////                [[NSUserDefaults standardUserDefaults] synchronize];
//                                    [self showToastWithMsg:@"注册成功！"];
//            }else {
//                                    [self showToastWithMsg:@"注册shib！"];
//            }
//        }
//    } failedBlock:^(NSError *error) {
//        NSLog(@"网络异常");
//    }];
    
    AFHTTPSessionManager* manage = [AFHTTPSessionManager manager];
        manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manage POST:kRegisterUrl parameters:param headers:@{@"Content-Type":@"application/json"} progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable dict) {

            if (dict) {
                //json 数据
                NSLog(@"dict:%@",dict);
                NSString* code = [NSString stringWithFormat:@"%@",dict[@"code"]];
                if ( [code isEqualToString:@"200"]) {
                    [self showToastWithMsg:@"注册成功！"];
                    
                    //保存数据，实名验证
                    [HWKeychain setPassword: dict[@"nickname"]  forService:kBundleId account:kUserName];
                    [HWKeychain setPassword: password  forService:kBundleId account:kPassword];
                    [HWKeychain setPassword: dict[@"dkToken"]  forService:kBundleId account:kToken];
                    NSString* idcard = [NSString stringWithFormat:@"%@",dict[@"idcard"]];
                    
                    if ([idcard isEqualToString:@"0"] && [dict[@"isShowIdcardClose"] isEqualToString:@"0"]) {
                        [[HWGameMgr shared] showRealNameView:@{@"username":username}];
                    }else{
                        [[HWGameMgr shared] showBall];
                    }
                }else {
                    NSString* msg = dict[@"msg"];
                    msg = msg!=NULL ? msg : @"注册失败，请稍后重试！";
                    [self showToastWithMsg:msg];
                    NSLog(@"失败:%@",dict[@"message"]);
                }
            }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"网络异常:%@",error);
    }];
}

#pragma mark - 登录
/*
{
 H5_dev: "UUID_1d383221e8f22e0f1cbfb82e2d4d2ecb"
 agentgame: "IOS.123-v1-1633017600"
 app_id: "1"
 device: {
     device_id: "UUID_1d383221e8f22e0f1cbfb82e2d4d2ecb",
     os: "ios"
 
 }
 device_id: "UUID_1d383221e8f22e0f1cbfb82e2d4d2ecb"
 os: "ios"
 password: "6GE3KHzS8Q1"
 username: "100055761"
*/
- (void)httpLogin:(NSDictionary*)data {
   
   NSString* username = [data objectForKey:@"username"];
   NSString* password = [data objectForKey:@"password"];
   NSString* app_id = kAppId;
   NSString* agentgame = kAgentgame;
   NSString* H5_dev = [HWGameMgr getDeviceString];
//    H5_dev = @"UUID_1d383221e8f22e0f1cbfb82e2d4d2ecb";
   
   NSDictionary* param = @{
       @"username":username,
       @"password":password,
       @"app_id":app_id,
       @"agentgame":agentgame,
       @"H5_dev":H5_dev,
       @"device":@{
           @"device_id":H5_dev,
           @"os":@"ios"
       }
                           
   };
    
    AFHTTPSessionManager* manage = [AFHTTPSessionManager manager];
//    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
//    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    [manage POST:kLoginUrl parameters:param headers:@{@"Content-Type":@"application/json"} progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable dict) {
        
            if (dict) {
                //json 数据
                NSLog(@"dict:%@",dict);
                NSString* code = [NSString stringWithFormat:@"%@",dict[@"code"]];
                if ( [code isEqualToString:@"200"]) {
                    [self showToastWithMsg:@"登录成功！"];
                    
                    //保存数据，实名验证
                    [HWKeychain setPassword: dict[@"nickname"]  forService:kBundleId account:kUserName];
                    [HWKeychain setPassword: password  forService:kBundleId account:kPassword];
                    [HWKeychain setPassword: dict[@"dkToken"]  forService:kBundleId account:kToken];
                    NSString* idcard = [NSString stringWithFormat:@"%@",dict[@"idcard"]];
                    
                    if ([idcard isEqualToString:@"0"] && [dict[@"isShowIdcardClose"] isEqualToString:@"0"]) {
                        [[HWGameMgr shared] showRealNameView:@{@"username":username}];
                    }else{
                        [[HWGameMgr shared] showBall];
                    }
                    
                }else {
                    NSString* msg = dict[@"msg"];
                    msg = msg!=NULL ? msg : @"登录失败，请稍后重试！";
                    [self showToastWithMsg:msg];
                    NSLog(@"登录失败:%@",dict[@"message"]);
                }
            }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showToastWithMsg:@"登录失败！未知错误！"];
        NSLog(@"登录失败:%@",error);
    }];
}
#pragma mark 实名认证
- (void)httpRealName:(NSDictionary*)data {
   
    NSString* dkToken = [HWKeychain passwordForService:kBundleId account:kToken];
    NSString* idcard = [data objectForKey:@"idcard"];
    NSString* truename = [data objectForKey:@"truename"];
    
    if (dkToken==NULL) {
        dkToken = @"";
        NSLog(@"dkToken null");
    }
    NSDictionary* param = @{
       @"dkToken":dkToken,
       @"idcard":idcard,
       @"truename":truename
    };
    
    AFHTTPSessionManager* manage = [AFHTTPSessionManager manager];
    [manage POST:kRealNameUrl parameters:param headers:@{@"Content-Type":@"application/json"} progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable dict) {
        
            if (dict) {
                //json 数据
                NSLog(@"dict:%@",dict);
                NSString* code = [NSString stringWithFormat:@"%@",dict[@"code"]];
                if ( [code isEqualToString:@"200"]) {
                    [self showToastWithMsg:@"认证成功！"];
                    
                    //显示小球浮窗
                    [[HWGameMgr shared] showBall];
                    [[HWGameMgr shared] hiddenAllView];
                    [[HWGameMgr shared] showBall];
                    
                }else {
                    NSString* msg = dict[@"msg"];
                    msg = msg!=NULL ? msg : @"认证失败，请重试！";
                    [self showToastWithMsg:msg];
                    NSLog(@"认证失败:%@",dict[@"message"]);
                    [self dealErrCode:code];
                }
            }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showToastWithMsg:@"认证失败！"];
        NSLog(@"认证失败:%@",error);
    }];
}
#pragma mark //获取验证码
- (void)httpGetCode:(NSDictionary*)data {
   
    NSString* dkToken = [HWKeychain passwordForService:kBundleId account:kToken];
    NSString* phoneNumber = [data objectForKey:@"phoneNumber"];
    
    if (dkToken==NULL) {
        dkToken = @"";
        NSLog(@"dkToken null");
    }
    NSDictionary* param = @{
       @"dkToken":dkToken,
       @"phoneNumber":phoneNumber
    };
    
    AFHTTPSessionManager* manage = [AFHTTPSessionManager manager];
    [manage POST:kGetCode parameters:param headers:@{@"Content-Type":@"application/json"} progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable dict) {
        
            if (dict) {
                //json 数据
                NSLog(@"dict:%@",dict);
                NSString* code = [NSString stringWithFormat:@"%@",dict[@"code"]];
                if ( [code isEqualToString:@"200"]) {
                    [self showToastWithMsg:@"发送成功！"];
                }else {
                    NSString* msg = dict[@"msg"];
                    msg = msg!=NULL ? msg : @"发送失败，请重试！";
                    [self showToastWithMsg:msg];
                    NSLog(@"发送失败:%@",dict[@"message"]);
                    [self dealErrCode:code];
                }
            }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showToastWithMsg:@"发送失败！"];
        NSLog(@"发送失败:%@",error);
    }];
}
#pragma mark //绑定手机号
- (void)httpBindPhone:(NSDictionary*)data {
   
    NSString* dkToken = [HWKeychain passwordForService:kBundleId account:kToken];
    NSString* phonenumber = [data objectForKey:@"phoneNumber"];
    NSString* verificationCode = [data objectForKey:@"verificationCode"];
    if (dkToken==NULL) {
        dkToken = @"";
        NSLog(@"dkToken null");
    }
    NSDictionary* param = @{
       @"dkToken":dkToken,
       @"phoneNumber":phonenumber,
       @"verificationCode":verificationCode
    };
    
    AFHTTPSessionManager* manage = [AFHTTPSessionManager manager];
    [manage POST:kBindPhoneUrl parameters:param headers:@{@"Content-Type":@"application/json"} progress:nil
     success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable dict) {
        
            if (dict) {
                //json 数据
                NSLog(@"dict:%@",dict);
                NSString* code = [NSString stringWithFormat:@"%@",dict[@"code"]];
                if ( [code isEqualToString:@"200"]) {
                    [self showToastWithMsg:@"绑定成功！"];
                    [[HWGameMgr shared] hiddenAllView];
                    [[HWGameMgr shared] showBall];
                    
                }else {
                    NSString* msg = dict[@"msg"];
                    msg = msg!=NULL ? msg : @"绑定失败，请重试！";
                    [self showToastWithMsg:msg];
                    NSLog(@"绑定失败:%@",dict[@"message"]);
                    [self dealErrCode:code];
                }
            }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showToastWithMsg:@"绑定失败！"];
        NSLog(@"绑定失败:%@",error);
    }];
}

#pragma mark //错误码处理
- (void)dealErrCode:(NSString*)code {
    //登录失效
    if ([code isEqualToString:@"411"]) {
        [self hiddenAllView];
        
        NSString* username = [HWKeychain passwordForService:kBundleId account:kUserName];
        NSString* password = [HWKeychain passwordForService:kBundleId account:kPassword];
        username = username==NULL ? @"" : username;
        password = password==NULL ? @"" : password;
        [self showLogin:@{@"username":username, @"password":password}];
    }else{
        
    }
}


#pragma mark ---------------------- UI ---------------------
#pragma mark -显示login
- (void)showLogin:(NSDictionary*)dic
{
    if (_loginView == NULL) {
        _loginView = [HWLoginView HWLoginView];
        [self.rootViewController.view addSubview:_loginView];
        
        _loginView.frame = self.rootViewController.view.frame ;
    }
    _loginView.hidden = false;
    [_loginView switchToLogin:dic];
    
    if (_userAgreementViewController == NULL) {
        _userAgreementViewController = [UserAgreementViewController new];
        _userAgreementViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
}

//显示login
- (void)hiddenLogin
{
    if (_loginView != NULL) {
        _loginView.hidden = true;
    }
}

#pragma mark -注册
- (void)showReg:(NSDictionary*)dic
{
    if (_loginView == NULL) {
        _loginView = [HWLoginView HWLoginView];
        [self.rootViewController.view addSubview:_loginView];
        
        _loginView.frame = self.rootViewController.view.frame ;
    }
    _loginView.hidden = false;
    [_loginView switchToReg:dic];
    
    if (_userAgreementViewController == NULL) {
        _userAgreementViewController = [UserAgreementViewController new];
        _userAgreementViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
}

#pragma mark - 悬浮球
//login after 显示悬浮球
- (void)showBall
{
    if (_ballView == NULL) {
        UIColor *color = [UIColor colorWithRed:0.50f green:0.89f blue:0.31f alpha:1.00f];
        _ballView =  [[ZYSuspensionView alloc] initWithFrame:CGRectMake(- 50.0 / 6, 200, 50, 50)
                                                       color:color
                                                    delegate:self];
        _ballView.leanType = ZYSuspensionViewLeanTypeHorizontal;
        [_ballView setTitle:@"" forState:UIControlStateNormal];
//        [self.rootViewController.view addSubview:_loginView];
        [_ballView show];
    }
    _ballView.hidden = false;
}

- (void)hiddenBall
{
    if (_ballView != NULL) {
        _ballView.hidden = true;
//        [_ballView removeFromScreen];
    }
}

- (void)showUserAgreement:(NSString*)url
{
    if (_userAgreementViewController == NULL) {
        _userAgreementViewController = [UserAgreementViewController new];
        _userAgreementViewController.modalPresentationStyle = UIModalPresentationOverFullScreen;
    }
//    _userAgreementViewController.modalPresentationStyle = UIModalPresentationNone;
    _userAgreementViewController.showUrl = url;
    [_userAgreementViewController clearWebView];
    [self.rootViewController presentViewController:_userAgreementViewController animated:YES completion:^{
        [_userAgreementViewController showWebViewWithUrl:url];
    }];
}
- (void)hiddenUserAgreement
{
    if (_userAgreementViewController != NULL) {
        [self.rootViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark -显示实名认证
- (void)showRealNameView:(NSDictionary*)dic
{
    if (_realName == NULL) {
        _realName = [HWRealNameView HWRealNameView];
        [self.rootViewController.view addSubview:_realName];
        
        _realName.frame = self.rootViewController.view.frame ;
    }
    _realName.hidden = false;
    [_realName updateData:dic];
}

//显示login
- (void)hiddenRealNameView
{
    if (_realName != NULL) {
        _realName.hidden = true;
    }
}

#pragma mark -显示shop兑换
- (void)showExchangeView:(NSDictionary*)dic
{
    if (_exchangeView == NULL) {
        _exchangeView = [HWExchangeView HWExchangeView];
        [self.rootViewController.view addSubview:_exchangeView];
        
        _exchangeView.frame = self.rootViewController.view.frame ;
    }
    _exchangeView.hidden = false;
    [_exchangeView updateData:dic];
}
- (void)hiddenExchangeView
{
    if (_exchangeView != NULL) {
        _exchangeView.hidden = true;
    }
}

#pragma mark 显示 toast
- (void)showToastWithMsg:(NSString *)msg
{
    [WHToast showMessage:msg originY:kWHToastScreenHeight*kToastPos duration:2.0 finishHandler:nil];
}
- (void)hiddenToast
{
}

#pragma mark 显示绑定手机号
- (void)showBindPhoneVew:(NSString*)account
{
    if (_bindPhoneView == NULL) {
        _bindPhoneView = [HWBindPhoneView HWBindPhoneView];
        [self.rootViewController.view addSubview:_bindPhoneView];
        
        _bindPhoneView.frame = self.rootViewController.view.frame ;
    }
    _bindPhoneView.hidden = false;
    [_bindPhoneView updateData:account];
    if (!kUseJs) {
        [[HWGameMgr shared] hiddenBall];
    }
}
- (void)hiddenBindPhoneVew
{
    if (_bindPhoneView != NULL) {
        _bindPhoneView.hidden = true;
    }
}

#pragma mark 个人中心
-(void)showUserViewWith:(NSDictionary*)dic;
{
    if (_userView == NULL) {
        _userView = [HWUserView HWUserView];
        [self.rootViewController.view addSubview:_userView];
        
        _userView.frame = self.rootViewController.view.frame ;
    }
    _userView.hidden = false;
    [_userView updateData:dic];
    if (!kUseJs) {
        [[HWGameMgr shared] hiddenBall];
    }
}
- (void)hiddenUserView
{
    if (_userView != NULL) {
        _userView.hidden = true;
    }
}

//显示login
- (void)hiddenAllView
{
    [self hiddenLogin];
    [self hiddenUserAgreement];
    [self hiddenRealNameView];
    [self hiddenExchangeView];
    [self hiddenBindPhoneVew];
    [self hiddenUserView];
}


#pragma mark ---------------------- delegate---------------------

#pragma mark - ZYSuspensionViewDelegate
- (void)suspensionViewClick:(ZYSuspensionView *)suspensionView
{
    NSLog(@" ball click %@",suspensionView.titleLabel.text);
    // test
//    [self showToastWithMsg:@"test toast" duration:2.0];
//    [self hiddenAllView];
    if (kUseJs) {
        [self callToJsWithMethed:@"SDKBallClickCallBack" andDic:@{}];
    } else {
        
        NSString* username = [HWKeychain passwordForService:kBundleId account:kUserName];
        NSString* phoneNumber = [HWKeychain passwordForService:kBundleId account:kPhoneNumber];
        username = username==NULL ? @"" : username;
        phoneNumber = phoneNumber==NULL ? @"" : phoneNumber;
        [self showUserViewWith:@{@"username":username,@"phoneNumber":phoneNumber}];
    }
    
//    NSString *rStr = [HWGameMgr randomString:11];
//    NSLog(@" ball rStr %@",rStr);
}


#pragma mark ---------------------- JS OC 通信接口---------------------
#pragma mark - js 调用方法
- (void)setExternalInterfacesWith:(EgretNativeIOS*)native{
    
    _native = native;
    __block HWGameMgr* this = self;
    
    [_native setExternalInterface:@"callFromJs" Callback:^(NSString* message) {
        
        NSLog(@"callFromJs json：%@", message);
        NSDictionary *dic = [this jsonToDicWith:message];
        NSLog(@"callFromJs dic：%@", dic);
        NSString* methed = [dic objectForKey:@"methed"];
        [this callFromJs:methed :dic];
    }];
    
    
    [_native setExternalInterface:@"gameGotoRegister" Callback:^(NSString* message) {
        
        NSLog(@"callFromJs json：%@", message);
        NSDictionary *dic = [this jsonToDicWith:message];
        NSLog(@"callFromJs dic：%@", dic);
        NSString* methed = [dic objectForKey:@"methed"];
        [this callFromJs:methed :dic];
    }];
    
}

// js 调用方法
- (void)callFromJs:(NSString*)methed :(NSDictionary*)dic{
    NSString * msg;
    if ([methed isEqualToString:@"SDKShowToast"]) {
        
        msg = [dic objectForKey:@"msg"];
        [[HWGameMgr shared] showToastWithMsg:msg];
        
    } else if ([methed isEqualToString:@"SDKShowUserPop"]) {
        
        [[HWGameMgr shared] showUserViewWith:dic];
        
    } else if ([methed isEqualToString:@"SDKClosePop"]) {
        
        [[HWGameMgr shared] hiddenAllView];
        
    } else if ([methed isEqualToString:@"SDKShowRealName"]) {
        
        [[HWGameMgr shared] showRealNameView:dic];
        
    } else if ([methed isEqualToString:@"SDKShowExchange"]) {
        
        [[HWGameMgr shared] showExchangeView:dic];
        
    } else if ([methed isEqualToString:@"SDKShowRegiste"]) {
        
        [[HWGameMgr shared] showReg:dic];
        
    } else if ([methed isEqualToString:@"SDKShowLogin"]) {
        
        [[HWGameMgr shared] showLogin:dic];
        
    } else if ([methed isEqualToString:@"SDKShowBall"]) {

        [[HWGameMgr shared] showBall];
        
    } else if ([methed isEqualToString:@"SDKHiddenBall"]) {

        [[HWGameMgr shared] hiddenBall];
    } else if ([methed isEqualToString:@"SDKShowBindPoneTimer"]) {
        NSString* count = [NSString stringWithFormat:@"%@",[dic objectForKey:@"count"]];
        if ([HWGameMgr shared].bindPhoneView) {
            [[HWGameMgr shared].bindPhoneView startWithTimerCount:[count integerValue]];
        }
    } else if ([methed isEqualToString:@"SDKStopBindPoneTimer"]) {
        if ([HWGameMgr shared].bindPhoneView) {
            [[HWGameMgr shared].bindPhoneView stopTimer];
        }
    }
}

// oc 调用js方法
//SDKShowLoginCallBack
//SDKShowRegisteCallBack
//SDKShowExchangeCallBack
//SDKShowRealNameCallBack
//SDKBindPhoneCallBack
//SDKExitCallBack
//SDKClickGetCodeCallBack
- (void)callToJsWithMethed:(NSString*)methed andDic:(NSDictionary*)dic{
    // msg
    [_native callExternalInterface:methed Value:[self dicToJsonWith:dic]];
}

- (NSDictionary *)jsonToDicWith:(NSString*)jsonString{

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:nil];
    NSLog(@"zk jsonToDicWith：%@", dic);
    return dic;
}

- (NSString*)dicToJsonWith:(NSDictionary*)dic{
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:nil];

    NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"zk dicToJsonWith：%@", str);
    return str;
}


@end
